// ITI 1120 Fall 2012, Lab 5, Supplemental Example
// Name: Gilbert Arbez, Student# 1234567


/**
 * This program finds the standard deviation of a set of values.
 */

class Lab5ExSupplemental
{
    public static void main (String[] args)
    {
        // DECLARE VARIABLES/DATA DICTIONARY 
        double[] arrValues; // reference to array of values for which to find average
        int n;              // Length of array
        double stdDev;      // Standard deviation of all values in array

        // PRINT OUT IDENTIFICATION INFORMATION        
        System.out.println();
        System.out.println("ITI 1120 Fall 2009, Lab 5, Supplemental Example");
        System.out.println("Name: Gilbert Arbez, Student# 1234567");
        System.out.println();      
       
        // READ IN GIVENS     
        System.out.println( "Please enter several real values on a line." );
        arrValues = ITI1120.readDoubleLine();
        
        // Find value of n from array length        
        n = arrValues.length;

        // Call problem solving method
        stdDev = calculateStdDev(arrValues,n);                                

        // PRINT OUT RESULTS AND MODIFIEDS
        System.out.println("The standard deviation is " + stdDev );
    }//end main
    
    
     /* 
     * Method:  calculateStdDev
     * Description: Calculates the standard deviation of the values in an array.
     * Givens: arr - a reference to an array of real values.
     *         n - the number of elements in the array.
     */
    public static double calculateStdDev(double[] arr, int n)
    {
       // Results
        double stdDev;       // Standard deviation of all values in x

       // Intermediates
        double sum;         // Running total of array values 
        int index;          // Index used to traverse the array.
        double average;     // The average of the array values.
        double sumSqrDiff;   // Running total of squares of differences from average 
       
       // Body
        // First calculate the average
        sum = 0.0;
        index = 0;        
        while(index < n)
        {
            sum = sum + arr[index];
            index = index + 1;
        }        
        average = sum/n;
        // Now the sum of the square of differences        
        sumSqrDiff = 0.0;
        index = 0;        
        while (index < n)
        {
            sumSqrDiff = sumSqrDiff + (arr[index] - average)*(arr[index] - average);
            index = index + 1;
        }
        // Finally the standard deviation
        stdDev = Math.sqrt(sumSqrDiff/(n-1) );
       // return the results
       return(stdDev);
    }
}//end class
